# -*- UTF-8 -*-
import pandas as pd

import matplotlib.pyplot as plt

from src.analyse_users import get_user_tags


def plot_tags_trend(csv_path, tag_list):
    df = pd.read_csv(csv_path)

    for tag_name in tag_list:
        tags_count_percentage = []
        row_tags_sum = df['row_tags_sum']
        for index, val in enumerate(df[tag_name]):
            # sum = sum + val
            tags_count_percentage.append(val / row_tags_sum[index])
        # period = pd.period_range(start="2008-08", end="2018-08", freq='M')
        # 设置时间标签显示格式
        plt.plot(df['periods'], tags_count_percentage, marker="o", label=tag_name)

    plt.ylabel('% of Stack Overflow Tags that month')
    plt.xticks(rotation=90)
    plt.title("Tags Trends")
    # 显示图例
    plt.legend()
    plt.show()


def plot_user_tags_stacked(user_tags_dataframe):
    """
    数目最多的五个标签，每月在总标签（数目）的比例
    :param user_tags_dataframe:
    :return:
    """
    # 统计每个标签的数目
    every_tag_count = pd.Series()
    for col in user_tags_dataframe.columns.values:
        sum = 0
        for index in user_tags_dataframe.index.values:
            sum += user_tags_dataframe.loc[index, col]
        every_tag_count[col] = sum
    # print(every_tag_count)
    # 统计每月的标签数目
    every_month_tag_count = pd.Series()
    for index  in user_tags_dataframe.index.values:
        sum = 0
        for col in user_tags_dataframe.columns.values:
            sum += user_tags_dataframe.loc[index, col]
        every_month_tag_count[index] = sum
    # print(every_month_tag_count)
    # 排序，寻找前 5 的标签
    every_tag_count = every_tag_count.sort_values(ascending=False)
    # print(every_tag_count)
    Y_df = pd.DataFrame(data=0, index=every_tag_count.index[:5], columns=user_tags_dataframe.index.values)


    for tag in Y_df.index.values:
        for period in Y_df.columns.values:
            Y_df.loc[tag, period] = user_tags_dataframe.loc[period, tag] / every_month_tag_count[period]

    # print(Y_df)

    fig, ax = plt.subplots()
    # X:N array  Y: M*N 2d array
    ax.stackplot(user_tags_dataframe.index.values, Y_df.values,
                 labels=Y_df.index.values)
    plt.ylabel("% of User's Tags that month")
    plt.xticks(rotation=90)
    plt.title("User's Top 5 Tag Trends")
    plt.legend()
    plt.show()


if __name__ == '__main__':
    df = get_user_tags(29407)
    # print(df)
    plot_user_tags_stacked(df)

